<?php
/**
 *  global.func.php 基本函数库
 * 
 * @version    0.1
 * @author    Hyperblue   i@kushu.net
 * @pubdate    2011-08-17 15:00
 */

/**
 * URL路径解析，pages 函数的辅助函数
 *
 * @param   string   $param   传入需要解析的变量 默认为，page={$page}
 * @param   string   $url   URL地址
 * @return   string
 */
function url_parse($param, $url = '') {
	if($url == '') $url = get_url();
	$pos = strpos($url, '?');
	if($pos === false) {
		$url .= '?'.$param;
	} else {
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($querystring, $params);
		$query_array = array();
		foreach($params as $k=>$v) {
			$query_array[$k] = $v;
		}
		$querystring = http_build_query($query_array).'&'.$param;
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	
	return $url;
}

/**
 * 字符截取 支持UTF8/GBK
 *
 * @param   string   $string
 * @param   integer   $length
 * @param   string   $dot
 * @return   string
 */
function cut_str($string, $length, $dot = '...') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	
	return $strcut.$dot;
}

/**
 * 获取文件后缀
 *
 * @param   string   $filename
 * @return   string
 */
function get_ext($filename){
	if(!empty($filename) && strpos($filename, '.') !== false) return end(explode(".",strtolower($filename)));
	else return false;
}

/**
 * 获取当前页面完整URL地址
 *
 * @return   string
 */
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

/**
 * 获取请求ip地址
 *
 * @return   string
 */
function get_ip() {
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	
	return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

/**
 * 产生随机字符串
 *
 * @param   int   $length   输出长度 
 * @param   string   $numeric   
 * @return   string   字符串
 */
function create_random($length, $numeric = 0){
	if(!isset($length)){
		$length = rand(2,4);
	}
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric){
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for ($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	
	return $hash;
}

/**
 * 将url转换成静态url
 */
function _url($action = '', $params = array (), $suffix = '', $file = 'index', $rewrite = BC_REWRITE) {
	$base_params = array('m' => ROUTE_M, 'c' => ROUTE_C, 'a' => ROUTE_A);
	if ($action) {
		if (stripos($action, '/') !== false) {
			$action_array = explode('/', $action);
			$base_params['m'] = isset($action_array[0]) ? $action_array[0] : 'index';
			$base_params['c'] = isset($action_array[1]) ? $action_array[1] : 'index';
			$base_params['a'] = isset($action_array[2]) ? $action_array[2] : 'index';
		} else {
			$base_params = array('m' => $action, 'c' => 'index', 'a' => 'index');
		}
	}
	
	if ($rewrite) {
		$params = array_merge($base_params, F_array_key2value($params));
		$url = ($file == 'index') ? BC_PATH : BC_PATH .$file . '/';
		if (!empty($params) && is_array($params)) $url .= implode('/', $params);  
		if (!empty($suffix)) $url .= '.' . $suffix;  
	 } else {
		$params = array_merge($base_params, $params);
		$url = ($file == 'index') ? BC_PATH : BC_PATH . $file;
		if (substr($url, -4) != '.php' && $file != 'index') $url .= '.php';  
		if (!empty($params) && is_array($params)) $url .= '?'.http_build_query($params);  
	} 
	
	return $url;  
} 

/**
 * 跳转
 */
function _redirect($url) {
	@header('location:'.$url);
	exit();
}

/**
 * 提示信息页面跳转，跳转地址如果传入数组，页面会提示多个地址供用户选择，默认跳转地址为数组的第一个值，时间为5秒。
 * @param string $msg 提示信息
 * @param mixed(string/array) $url_forward 跳转地址
 * @param int $ms 跳转等待时间
 */
function _showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
    if (defined('IN_ADMIN')) {
        include(admin::admin_tpl('showmessage', 'admin'));
    } else {
        include(template('sns', 'message'));
    }
    exit;
}
?>
